from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List
from ..database import get_db
from ..auth.jwt_handler import get_current_user
from ..models.user import User
from ..models.model import ModelConfig
from pydantic import BaseModel
from typing import Optional, Any, Dict
import httpx
import os
import time
from ..config import CHANNEL_API_CONFIG, get_current_timestamp

router = APIRouter(prefix='/models', tags=['models'])

#获取当前时间戳
def get_current_timestamp():
    return int(time.time())

# 渠道信息模型
class ChannelInfo(BaseModel):
    id: int
    name: str
    models: str
    base_url: str
    key: str
    status: int
    balance: float
    used_quota: int
    type: int
    group: str

# 渠道信息响应模型
class ChannelResponse(BaseModel):
    code: int
    msg: str
    data: List[ChannelInfo]

# 模型信息模型
class ModelInfo(BaseModel):
    model: str
    priority: int
    channel_id: int
    enabled: bool
    group: str

# 模型信息响应模型
class ModelResponse(BaseModel):
    code: int
    msg: str
    data: List[ModelInfo]

@router.get("/channels", response_model=ChannelResponse)
async def get_channels(
    current_user: User = Depends(get_current_user)
):
    print(f"获取渠道信息")
    """
    获取渠道信息接口
    从外部API获取渠道信息
    """
    try:
        print("=== 环境变量调试 ===")
        print(f"GET_CHANNEL_URL: {os.getenv('GET_CHANNEL_URL')}")
        print(f"PROMPT_API_USER_KEY: {os.getenv('PROMPT_API_USER_KEY')}")
        print(f"PROMPT_API_AUTHORIZATION: {os.getenv('PROMPT_API_AUTHORIZATION')}")
        print("==================")

        # 调用外部API获取渠道信息
        headers = {
            'UserKey': os.getenv('PROMPT_API_USER_KEY'),
            'YmDate': str(get_current_timestamp()),
            'Authorization': os.getenv('PROMPT_API_AUTHORIZATION')
        }
        
        url = os.getenv('GET_CHANNEL_URL')

        async with httpx.AsyncClient() as client:
            response = await client.get(
                url,
                headers=headers,
                timeout=30.0
            )
            print(f"调用获取渠道信息接口，返回值response={response.json()}")

            if response.status_code == 200:
                return response.json()
            else:
                raise HTTPException(
                    status_code=status.HTTP_502_BAD_GATEWAY,
                    detail="外部渠道API调用失败"
                )
                
    except httpx.TimeoutException:
        raise HTTPException(
            status_code=status.HTTP_504_GATEWAY_TIMEOUT,
            detail="外部渠道API调用超时"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取渠道信息失败: {str(e)}"
        )

@router.get("/models/{channel_id}", response_model=ModelResponse)
async def get_channel_models(
    channel_id: int,
    current_user: User = Depends(get_current_user)
):
    print(f"根据渠道获取模型信息")
    """
    获取指定渠道的模型信息接口
    从外部API获取指定渠道的模型信息
    """
    try:
        # 调用外部API获取指定渠道的模型信息
        headers = {
            'UserKey': CHANNEL_API_CONFIG['user_key'],
            'YmDate': str(get_current_timestamp()),
            'Authorization': CHANNEL_API_CONFIG['authorization']
        }
        
        # 构建请求URL，添加channel_id参数
        url = CHANNEL_API_CONFIG['get_model_url']+f"?channel_id={channel_id}"
        
        print(f"headers={headers}")
        print(f"get_channel_url={url}")

        async with httpx.AsyncClient() as client:
            response = await client.get(
                url,
                headers=headers,
                timeout=30.0
            )
            
            if response.status_code == 200:
                return response.json()
            else:
                raise HTTPException(
                    status_code=status.HTTP_502_BAD_GATEWAY,
                    detail="外部模型API调用失败"
                )
                
    except httpx.TimeoutException:
        raise HTTPException(
            status_code=status.HTTP_504_GATEWAY_TIMEOUT,
            detail="外部模型API调用超时"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取模型信息失败: {str(e)}"
        )

class ModelCreate(BaseModel):
    channel_id: Optional[int] = None
    channel: Optional[str] = None
    model: str
    temperature: Optional[float] = 1.0
    max_tokens: Optional[int] = 2048
    top_p: Optional[float] = 1.0
    presence_penalty: Optional[float] = 0.0
    frequency_penalty: Optional[float] = 0.0
    n: Optional[int] = 1
    stop: Optional[List[str]] = None
    logit_bias: Optional[Dict[str, Any]] = None
    stream: Optional[bool] = False
    response_format: Optional[str] = None
    reasoning_effort: Optional[str] = None
    endpoint_url: Optional[str] = None
    file_path: Optional[str] = None
    api_key: Optional[str] = None

class ModelResponse(ModelCreate):
    id: int

    class Config:
        orm_mode = True

@router.post('/', response_model=ModelResponse)
def create_model(payload: ModelCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    model_cfg = ModelConfig(**payload.dict())
    db.add(model_cfg)
    db.commit()
    db.refresh(model_cfg)
    return model_cfg

@router.get('/', response_model=List[ModelResponse])
def list_models(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    return db.query(ModelConfig).order_by(ModelConfig.created_at.desc()).all()

@router.get('/{model_id}', response_model=ModelResponse)
def get_model(model_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    model = db.query(ModelConfig).filter(ModelConfig.id == model_id).first()
    if not model:
        raise HTTPException(status_code=404, detail='模型不存在')
    return model
